// toastr.success('注册成功')


// 需求1： 点击切换

let loginA = document.querySelector('.login a')
let registerA = document.querySelector('.register a')
let login = document.querySelector('.login')
let register = document.querySelector('.register')
let inp1 = document.querySelector('.register [name="username"]')
let inp2 = document.querySelector('.register [name="password"]')
let inp3 = document.querySelector('.login [name="username"]')
let inp4 = document.querySelector('.login [name="password"]')
console.log(inp1,inp2,inp3,inp4)


// 绑定点击事件
loginA.onclick = function(){
  login.style.display = 'none'
  register.style.display = 'block'
}

registerA.onclick = function(){
  register.style.display = 'none'
  login.style.display = 'block'

}

  // 非空判断
  function verifyInput(item,text1,reg,text2){
    item.onkeyup = function(){
      if(this.value == ''){
        this.nextElementSibling.style.display = 'block'
        this.nextElementSibling.innerHTML = text1
        return // 如果满足正则校验条件, 后面代码就不用执行了
      }else{
       this.nextElementSibling.style.display = 'none'
       this.nextElementSibling.innerHTML = ''
      }
   
      // 需求2：正则校验
      if(reg.test(this.value)){
       //如果通过正则校验就隐藏span
       this.nextElementSibling.style.display = 'none'
       this.nextElementSibling.innerHTML = ''
      }else{
         // 没通过就显示
         this.nextElementSibling.style.display = 'block'
         this.nextElementSibling.innerHTML = text2
      }
    }
  }
  verifyInput(inp1,'用户名不得为空',/^\S{2,15}$/,'用户名必须在2~15位之间')
  verifyInput(inp2,'密码不得为空',/^\S{6,15}$/,'密码必须在6~15位之间')
  verifyInput(inp3,'用户名不得为空',/^\S{2,15}$/,'用户名必须在2~15位之间')
  verifyInput(inp4,'密码不得为空',/^\S{6,15}$/,'密码必须在6~15位之间')


  
// 需求3： 注册功能

let form1 = document.querySelector('.register form')

let form2 = document.querySelector('.login form')

form1.addEventListener('submit',function(e){
  // 阻止表单默认提交事件
  e.preventDefault()

  // 发送ajax请求
  axios({
    method:'POST',
    url:'/api/register',
    data:{
      username:inp1.value,
      password:inp2.value
    }
  }).then(({data:res})=>{
     //判断状态码是否为1
/*      if(res.code == 1){
       return toastr.warning(res.message)
     } */
     if(res.code == 0){
      toastr.success('恭喜你,注册成功')
      form1.reset()
      location.href = './login.html'
     }
  })
})


// 需求四： 登录功能
form2.addEventListener('submit',function(e){
  e.preventDefault()

  axios({
    method:'post',
    url:'/api/login',
    data:{
      username:inp3.value,
      password:inp4.value
    }
  }).then(({data:res})=>{
     // 状态码判断
/*      if(res.code == 1){
        return toastr.warning(res.message)
     } */
     if(res.code == 0){
      toastr.success('恭喜你，登录成功')
      location.href = './index.html'
      localStorage.setItem('token',res.token)
     }
    
  })
})
  







